<template>
  <div>
    <el-dialog
      title="分配权限"
      width="50%"
      @close="setRightDialogClosed"
      :visible.sync="SetRightDialogVisible">
      <!-- 树形控件 -->
      <div class="rightTree">
        <el-tree :data="rightData" :props="TreeProps"
          node-key="id"
          ref="treeRef"
          default-expand-all
          :default-checked-keys="defKeys"
          show-checkbox>
        </el-tree>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="SetRightDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="setRight">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'VueShopSetRight',
  props:['rightsList','defKeys','roleId'],
  data() {
    return {
      // 控制分配权限对话框的显示与隐藏
      SetRightDialogVisible:false,
      // 权限树源数据
      rightData:[],
      // 树形控件的属性绑定对象 
      TreeProps:{
        label: 'authName',
        children: 'children',
      },
      // 默认选择节点
      defKeysData:[],
    };
  },
  // 监听父组件传值
  watch:{
    rightsList(data){
      this.rightData = data;
    },
    defKeys(data){
      this.defKeysData = data;
    }
  },
  methods: {
    /**
     * @name handleClose()
     * @监听关闭分配权限对话框
     */
     setRightDialogClosed(){
      this.$emit('setRightDialogClosed');
     },
     /**
      * @name
      * @点击为角色分配权限
      */
     async setRight(){
      const keys = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys(),
      ];
      const idStr = keys.join(',');
      const {data:res} = await this.$http.post(`roles/${this.roleId}/rights`,{rids:idStr});
      if(res.meta.status !== 200){
        return this.$message.error('分配权限失败')
      }
      this.$message.success('分配权限成功');
      this.$emit('getRolesList');
      this.SetRightDialogVisible = false;
     }
  },
};
</script>

<style lang="less" scoped>

</style>